# -*- coding: utf-8 -*- 
"""
Created by hcx on 17-8-3 下午4:19.
@author: 胡超翔
"""
from __future__ import absolute_import
from __future__ import unicode_literals

import datetime
import logging

from autodeploy.apps.common.use_celery import fact_msg
from autodeploy.apps.operation.models import OperationLog
from autodeploy.apps.operation.views import create_log
from autodeploy.settings.celery import app

# from autodeploy.apps.common.use_celery import use_ansible
from autodeploy.apps.common.ansible_base import AnsibleTask
from autodeploy.settings import MEDIA_ROOT

logger = logging.getLogger(__name__)


# def run_ansible(server_list, group_name='all', playbooks=None, variable=None):
#     try:
#         result = use_ansible(server_list, group_name=group_name, playbooks=playbooks, variable=variable, )
#     except Exception as e:
#         logger.error(e)
#         print e
#     return result
@app.task()
def use_ansible(server_list, group_name='all', playbooks=None, variable=None, ):
    """
    
    :param server_list: 服务器列表
    :param group_name:用户组名
    :param playbooks:剧本文件的对象，即PlayBooksFile表
    :param variable:剧本内的变量，以字典方式传入，例如:若variable={'item':item}:
            ---
            -host:xxx
            -task:
                -name:{{item}}
    :return:
    """
    result = {'status': [], 'msg': {}}
    logger.info('run start*********************************************')
    for i in range(len(server_list)):
        server = server_list[i]
        operation_log = OperationLog.objects.create(server=server_list[i], server_ip=server_list[i].ip)
        if not playbooks:
            playbooks = MEDIA_ROOT + '/task/information.yaml'
            ansible = AnsibleTask([server_list[i].ip], [playbooks], user=server_list[i].ssh_user,
                                  password=server_list[i].ssh_password, group_name=group_name,
                                  variable=variable, port=server_list[i].port,operation_log=operation_log)
            status, msg = ansible.run()
        else:
            ansible = AnsibleTask([server_list[i].ip], [playbooks.path], user=server_list[i].ssh_user,
                                  password=server_list[i].ssh_password, group_name=group_name,
                                  variable=variable, port=server_list[i].port,operation_log=operation_log)
            # 若存在playbook,将其关联到日志
            operation_log.play_books = playbooks.playbooks
            operation_log.books_name = playbooks.playbooks.name
            operation_log.version = playbooks.version
            operation_log.save()
            status, msg = ansible.run()
        result['status'].append(status)
        result['msg'] = msg
        # 根据剧本执行结果，创建记录
        if msg['success']['ok'] or msg['success']['change'] or msg['success']['fact']:
            
            if msg['success']['ok']:
                for re in msg['success']['ok']:
                    logger.info(u'成功提示:%s' % re)
                    # create_log(operation_log, result=str(re), status='success',detail_status='success')
            if msg['success']['change']:
                for re in msg['success']['change']:
                    # create_log(operation_log, result=str(re), status='success',detail_status='success')
                # if playbooks == MEDIA_ROOT + '/task/information.yaml':
                #     change_msg(server, msg['success']['change'], playbooks=playbooks, status='information')
                # else:
                #     change_msg(server, msg['success']['change'], playbooks=playbooks)
                    logger.info(u'成功提示:%s' % re)
            if msg['success']['fact']:
                for re in msg['success']['fact']:
                    r = ''
                    if playbooks == MEDIA_ROOT + '/task/information.yaml':
                        if msg['success']['fact']:
                            # 获取硬件信息时
                            r = fact_msg(server, re)
                    if r:
                        logger.error(u'提示:%s' % r)
                        # create_log(operation_log, result=r, status='success',detail_status='success')
                    else:
                        if len(str(re)) > 1000:
                            r = u"数据太长无法存入数据库"
                        else:
                            r = re
                    logger.info(u'提示:%s' % r)
                        # create_log(operation_log, result=r, status='success',detail_status='success')
        if msg['fatal']:
            for re in msg['fatal']:
                # create_log(operation_log, result=str(re), status='defeat',detail_status='failed')
                logger.info(u'剧本运行失败,错误提示:%s' % re)
        if msg['unreachable']:
            for re in msg['unreachable']:
                # create_log(operation_log, result=str(re), status='defeat',detail_status='unreachable')
                logger.info(u'剧本运行失败,错误提示:%s' % re)
        if msg['success']['ok'] == [] and msg['success']['change'] == [] and msg['success']['fact'] == [] and msg[
            'fatal'] == [] and msg['unreachable']:
            logger.info(u'剧本运行结果有误,系统错误')
            create_log(operation_log, result='剧本运行结果有误，系统或剧本错误', status='defeat',detail_status='default')
        operation_log.end_time = datetime.datetime.now()
        operation_log.save()
    logger.info('run over*********************************************')
    
    return result
